//
//  AppDelegate.m
//  UI17- SandBox
//
//  Created by 韩旭 on 16/8/5.
//  Copyright © 2016年 lanou. All rights reserved.
//

#import "AppDelegate.h"
#import "Book.h"
@interface AppDelegate ()

@end

@implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    //  什么是 SandBox(沙盒)
    //    1. Docments (文件文档用户数据存储， 用户主动数据存储)
    //    2. Library (资源， 一般用来存放，程序员要存储的一些数据)
    //    3. tmp （临时目录， 下载的临时文件一般放这里）
    //    Library -> 有 Caches（缓存文件） 和 Preterences（用户信息，用户设置， NSUserDefaults）
    [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"isLogin"];
    [[NSUserDefaults standardUserDefaults] synchronize];
    //  2.  获取沙盒路径
    //    快捷获取到对应的目录的 c 函数
    //   根目录 家目录
    //  NSLog(@"%@", NSHomeDirectory());
    //  临时目录 tmp
    //  NSLog(@"%@",  NSTemporaryDirectory());
    //    获取到对应的目录 C 函数
    //    1. 参数1. 搜索哪个文件夹路径 (NSDocumentDirectory ，NSLibraryDirectory , NSCachesDirectory ，常用的)
    //    2. 参数2. 在用户作用域下搜索
    //    3. 参数3. yes Or no, YES 代表绝对路径（基本上都用绝对路径），NO代表相对路径（~）
    NSArray *arr = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSLog(@"%@", [arr firstObject]);
    
    //    NSBundle .app 文件包
    //    NSLog(@"%@", [NSBundle mainBundle]);
    //    1. 简单文件读写 Input输入 Output输出
    NSString *string = @"Hello , I/O File";
    //    一般拼接路径时候, 使用
    //    NSString *writePath = [[arr firstObject] stringByAppendingString:@"/HELLO.txt"];
    //  将文字写入本地
    NSString *writePath =[[arr firstObject] stringByAppendingPathComponent:@"Hello.tex"];
    NSError *error = nil;
    BOOL isSuccess = [string writeToFile:writePath atomically:YES encoding:NSUTF8StringEncoding error:&error];
    if (error) {
        NSLog(@"存储失败");
    } else {
        NSLog(@"恭喜成功");
    }
    //    2.> 读取路劲对应的文字
    NSError *readError = nil;
    NSString *readString = [NSString stringWithContentsOfFile:writePath encoding:NSUTF8StringEncoding error:&readError];
    NSLog(@"%@", readString);
    //    将 数组 写入本地文件
    NSArray *arrPath = @[@"你家", @"李其昌", @"王黄"];
    NSString *arrayPath = [[arr firstObject] stringByAppendingPathComponent:@"name.plist"];
    BOOL isArray = [arrPath writeToFile:arrayPath atomically:YES];
    if (isArray) {
        NSLog(@"写入成功");
    } else {
        NSLog(@"写入失败");
    }
    //    将 数组 读入
    NSArray *arr2 = [NSArray arrayWithContentsOfFile:arrayPath];
    NSLog(@"%@", arr2);
    
    //    将字典的存储 和 读写
    NSDictionary *dic = [NSDictionary dictionary];
    dic = @{@"name" : @"小红", @"age" : @14, @"sex" : @"男"};
    
    //    存入数据
    NSString *dicPath = [[arr firstObject] stringByAppendingPathComponent:@"dic.plist"];
    BOOL isDic = [dic writeToFile:dicPath atomically:YES];
    if (isDic) {
        NSLog(@"存入成功");
    } else {
        NSLog(@"存入失败");
    }
    //    读取数据
    NSLog(@"%@", [NSDictionary dictionaryWithContentsOfFile:dicPath]);
    
    //    7> 将Data类型写入本地
    UIImage *image = [UIImage imageNamed:@"newsPic1"];
    NSData *data = UIImageJPEGRepresentation(image, 0.1);
    //    NSLog(@"%@", data);
    //    将图片转化成PNG格式
    UIImagePNGRepresentation(image);
    //
    NSString *dataPath = [[arr firstObject] stringByAppendingPathComponent:@"dataImae"];
    BOOL isData = [data writeToFile:dataPath atomically:YES];
    if (isData) {
        NSLog(@"储存成功");
    } else {
        NSLog(@"存储失败");
    }
    //    nsdata 类型 读入
    NSData *dataImage = [NSData dataWithContentsOfFile:dataPath];
    NSLog(@"%@", dataImage);
    
    //    将Data转化成图片
//        UIImage *fileImage = [UIImage imageNamed:dataImage];
    
    //    UIImagePNGRepresentation(image);
    //    2. 复杂对象文件的读写，自定义类型 （存储）
    //    归档/反规当， 序列化/反序列化
    //    1.> 归档 将 对象 存储到本地
    Book *book = [Book new];
    book.bookName = @"金瓶梅";
    book.bookAuthor = @"李其昌";
    book.price = @"998";
    book.bookAddress = @"小嘎啦胡同";
   
    NSString *bookPath = [[arr firstObject] stringByAppendingPathComponent:@"book.plist"];
 BOOL isKey = [NSKeyedArchiver archiveRootObject:book toFile:bookPath];
    if (isKey) {
        NSLog(@"存入成功");
    } else {
        NSLog(@"存入失败");
    }
//   2.> 反归档
  Book *hunagBook =[NSKeyedUnarchiver unarchiveObjectWithFile:bookPath];
    NSLog(@"%@", hunagBook.bookAuthor);
    
//    如果对象想要实现归档和反归档
//    1. 对象对应的类需要签订<NSCoding>
//    2. 实现协议方法
//    1.> initWithCoder 反归档用
//    2.> encodeWithCoder 归档用
//    3. 归档时，使用 NSKeyedArchiver
//    4. 反归档时， 使用NSKeyedUnarchiver
    
    
    
    return YES;
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

@end
